﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Leadtools;
using Leadtools.Codecs;
using Leadtools.ImageProcessing;
using Leadtools.WinForms;
using Microsoft.Office.Interop.Excel;
using MINERP.BLL.DisjoinProForOutShop;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.MODEL.OverOrder;
using Application = System.Windows.Forms.Application;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;

namespace MINERP.DisjoinProForOutShop.Forms
{
    public partial class FrmExportOutProduct : Form
    {
        public FrmExportOutProduct()
        {
            InitializeComponent();
        }
        public FrmExportOutProduct(List<OverOrderView> inList, String inGridName)
        {
            InitializeComponent();
            ExportList = inList;
            ExprotGridName = inGridName;
        }

        List<OverOrderView> ExportList = new List<OverOrderView>();
        private string ExprotGridName = "";
        ExportOutProductBLL _bll = new ExportOutProductBLL();
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "选择导出委外文件的报表";
            //folderBrowserDialog.RootFolder = Environment.SpecialFolder.Startup;
            folderBrowserDialog.ShowNewFolderButton = true;
            if (DialogResult.OK == folderBrowserDialog.ShowDialog())
            {
                textEdit1.Text = folderBrowserDialog.SelectedPath;
                Properties.Settings.Default.ExportProductPath = folderBrowserDialog.SelectedPath;
                Properties.Settings.Default.Save();
            }
        }

        private void FrmImportOutProduct_Load(object sender, EventArgs e)
        {
            string importPath = Properties.Settings.Default.ExportProductPath;
            if (string.IsNullOrEmpty(importPath))
            {
                textEdit1.Text = Application.StartupPath.ToString() + "\\委外导出目录";
            }
            t = new Thread(new ThreadStart(ExportProduct));
        }
        /// <summary>
        /// 移动文件，文件夹
        /// </summary>
        /// <param name="src"></param>
        /// <param name="dst"></param>
        /// <param name="flag">1如果文件存在，则替换；2如移动到不同的卷，则复制文件并删除原来的文件；3移动操作在系统重启后才真正执行</param>
        /// <returns></returns>
        [DllImport("kernel32", EntryPoint = "MoveFileEx", CharSet = CharSet.Unicode)]
        public static extern bool MoveFile(string src, string dst, long flag);
        Thread t = null;
        private void simpleButtonOK_Click(object sender, EventArgs e)
        {
            this.simpleButtonOK.Enabled = false;
            if (t.ThreadState != System.Threading.ThreadState.Running)
            {
                t.Start();
            }
            else
            {

            }


        }

        private bool TheadEnable = false;
        public void ExportProduct()
        {
            ExcelEdit excelEdit = new ExcelEdit();
            excelEdit.Create();

            string ExportRootPath = textEdit1.Text.Trim();
            string OutShopName = ExportList.FirstOrDefault().OutShopName;
            string DateFolder = DateTime.Today.ToString("yyyyMMdd");
            string TimeFolder = DateTime.Now.TimeOfDay.ToString().Replace(':', ' ');
            string currOperPath = OutShopName + DateTime.Now.ToString("yyyyMMddHHmmss") + ExprotGridName;
            string savePath = ExportRootPath + "\\" + OutShopName + "\\" + DateFolder + "\\" + currOperPath;
            string rarSavePath = ExportRootPath + "\\" + OutShopName + "\\" + DateFolder;
            if (!Directory.Exists(savePath))//创建委外商的目录
            {


                Directory.CreateDirectory(savePath);
                WriteInfo("创建目录成功", Color.Black);
            }
            try
            {
                SetProcessPoint(2);
                int intCurrPoint = 2;
                int productStep = 98 / ExportList.Count;

                int photoInfoStartRow = 12;/// 照片信息开始的行
                RasterCodecs.Startup();
                RasterCodecs codecs = new RasterCodecs();
                CodecsThumbnailOptions option = new CodecsThumbnailOptions();
                foreach (OverOrderView view in ExportList)//每个产品对应一个sheet
                {
                    string strSheetName = view.OrderProductId + view.OrderProductName;
                    if (strSheetName.Length > 30)
                    {
                        strSheetName = strSheetName.Substring(0, 29);
                        strSheetName = strSheetName.Replace('*', 'X');
                        WriteInfo("产品名称超长，将截取前29个字符", Color.Black);
                    }

                    Worksheet currSheet = excelEdit.AddSheet(strSheetName);
                    WriteInfo("创建【" + view.OrderProductName + "】的Sheet成功", Color.Black);
                    intCurrPoint += 2;
                    SetProcessPoint(intCurrPoint);
                    //产品信心头
                    //excelEdit.SetCellProperty(currSheet, 3, 1, 3, 1, 12, "宋体", Constants.xlAutomatic, Constants.xlCenter);
                    excelEdit.SetCellTatolProperty(currSheet, 1, 1, photoInfoStartRow, 1);//
                    // excelEdit.SetCellTatolProperty(currSheet, 1, 9, 6, 9);
                    //excelEdit.SetCellTatolProperty(currSheet, 1, 9, 6, 9);
                    //excelEdit.SetCellTatolProperty(currSheet, 9, 1, 7, 8);

                    for (int i = 1; i < photoInfoStartRow; i++)
                    {
                        excelEdit.UniteCells(currSheet, i, 2, i, 8);
                        excelEdit.SetCellContentProperty(currSheet, i, 2, i, 8);
                    }


                    excelEdit.SetCellValue(currSheet, 1, 1, "产品名称：");
                    excelEdit.SetCellValue(currSheet, 1, 2, view.OrderProductName);
                    excelEdit.SetCellValue(currSheet, 2, 1, "产品ID：");
                    excelEdit.SetCellValue(currSheet, 2, 2, view.OrderProductId);
                    excelEdit.SetCellValue(currSheet, 3, 1, "商户名称：");
                    excelEdit.SetCellValue(currSheet, 3, 2, view.ShopName);
                    excelEdit.SetCellValue(currSheet, 4, 1, "客人名称：");
                    excelEdit.SetCellValue(currSheet, 4, 2, view.CtmName);
                    excelEdit.SetCellValue(currSheet, 5, 1, "产品规格：");
                    excelEdit.SetCellValue(currSheet, 5, 2, view.Size);
                    excelEdit.SetCellValue(currSheet, 6, 1, "产品份数：");
                    excelEdit.SetCellValue(currSheet, 6, 2, view.ProductNum);
                    excelEdit.SetCellValue(currSheet, 7, 1, "照片数量：");
                    excelEdit.SetCellValue(currSheet, 7, 2, view.photoNum);
                    excelEdit.SetCellValue(currSheet, 8, 1, "委外时间：");
                    excelEdit.SetCellValue(currSheet, 8, 2, view.CreateTime);
                    excelEdit.SetCellValue(currSheet, 9, 1, "委外预取件时间：");
                    excelEdit.SetCellValue(currSheet, 9, 2, view.PreFetchTime);
                    excelEdit.SetCellValue(currSheet, 10, 1, "预取件时间：");
                    excelEdit.SetCellValue(currSheet, 10, 2, view.FetchTime);
                    excelEdit.SetCellValue(currSheet, 11, 1, "备注：");
                    excelEdit.SetCellValue(currSheet, 11, 2, view.Remark + view.OutRemark);

                    excelEdit.UniteCells(currSheet, photoInfoStartRow, 1, photoInfoStartRow, 8);//照片信息头部        
                    excelEdit.SetCellTatolProperty(currSheet, photoInfoStartRow + 1, 1, photoInfoStartRow + 1, 8);
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow, 1, "【照片列表】");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 1, "照片ID");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 2, "照片名称");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 3, "规格(英寸)");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 4, "规格(厘米)");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 5, "份数");
                    excelEdit.SetCellValue(currSheet, photoInfoStartRow + 1, 6, "缩略图");
                    excelEdit.UniteCells(currSheet, photoInfoStartRow + 1, 6, photoInfoStartRow + 1, 8);
                    //SetProcessPoint(5);
                    WriteInfo("产品【" + view.OrderProductName + "】信息写入成功", Color.Black);
                    intCurrPoint += 2;
                    SetProcessPoint(intCurrPoint);
                    List<PhotoInfo_Info> photoList = _bll.GetPhotosBuProductid(view.OrderProductId);
                    WriteInfo("获取产品【" + view.OrderProductName + "】的照片信息成功", Color.Black);
                    intCurrPoint += 2;
                    SetProcessPoint(intCurrPoint);

                    option.LoadStamp = true;
                    option.MaintainAspectRatio = true;
                    option.Resample = true;
                    //option.ForceSize = true;
                    //option.bi
                    RasterImage img;
                    int intCount = 0;
                    int iCount = 0;
                    int photoStep = (productStep - 6) / photoList.Count;
                    foreach (PhotoInfo_Info photo in photoList)
                    {
                        intCount = 8 * iCount;//放下2寸图片大小
                        iCount++;
                        //写入照片信息
                        string photoFullPath = savePath + "\\" + photo.PhotoId+photo.PhotoName;
                        excelEdit.SetCellValue(currSheet, photoInfoStartRow + 2 + intCount, 1, photo.PhotoId);
                        excelEdit.SetCellValue(currSheet, photoInfoStartRow + 2 + intCount, 2, photo.PhotoName);
                        excelEdit.SetCellValue(currSheet, photoInfoStartRow + 2 + intCount, 3, photo.PhtotoSizeInch);
                        excelEdit.SetCellValue(currSheet, photoInfoStartRow + 2 + intCount, 4, photo.PhotoSizeCm);
                        excelEdit.SetCellValue(currSheet, photoInfoStartRow + 2 + intCount, 5, photo.TotalNum);
                        WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】信息写入成功", Color.Black);
                        //拷贝文件
                        if (!File.Exists(photo.PicPath))
                        {
                            WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】不存在", Color.Red);

                        }
                        try
                        {
                            if (File.Exists(photoFullPath))
                            {
                                File.Delete(photoFullPath);
                            }
                            File.Copy(photo.PicPath, photoFullPath);
                        }
                        catch (Exception exxx)
                        {
                            WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】拷贝失败,查看目录是否打开。", Color.Red);

                        }
                        WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】拷贝成功", Color.Black);
                        if (!File.Exists(photoFullPath))
                        {
                            WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photoFullPath + "】文件不存在。", Color.Red);
                        }
                        else
                        {
                            string picTag = ".JPEG.JPG.TIF.BMP.TIFF";
                            string currExtent = photoFullPath.Substring(photoFullPath.LastIndexOf('.'));
                            if (picTag.Contains(currExtent.ToUpper()))
                            {
                                try
                                {

                                    img = codecs.Load(photoFullPath);
                                    //int widthS = 144;
                                    //int heigthS = Convert.ToInt32(photo.Height * 144 / photo.Width);

                                    int heigthS = 100;
                                    int widthS = Convert.ToInt32(photo.Width * heigthS / photo.Height);
                                    SizeCommand command = new SizeCommand();
                                    command.Width = widthS;
                                    command.Height = heigthS;
                                    command.Flags = RasterSizeFlags.Resample;
                                    command.Run(img);

                                    codecs.Save(img, Application.StartupPath + "\\ExportProductTemp.jpg", RasterImageFormat.Jpeg, 24);
                                    WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】转存成功", Color.Black);

                                    img.Dispose();
                                    //imgSmall.Dispose();
                                    Range range = currSheet.get_Range(currSheet.Cells[photoInfoStartRow + 2 + intCount, 6], currSheet.Cells[photoInfoStartRow + 2 + intCount, 6]);

                                    //excelEdit.SetCellValue(currSheet,  11 + intCount,6, photo.PhotoName);
                                    //range.Select();
                                    //Microsoft.Office.Interop.Excel.Pictures pic = (Microsoft.Office.Interop.Excel.Pictures)currSheet.Pictures(System.Reflection.Missing.Value);
                                    //pic.Insert(Application.StartupPath + "\\ExportProductTemp.jpg", System.Reflection.Missing.Value);

                                    // WriteInfo("正在写入产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】小图", Color.Black);
                                    excelEdit.InsertPictures(currSheet, Application.StartupPath + "\\ExportProductTemp.jpg", Convert.ToSingle(range.Left), Convert.ToSingle(range.Top), widthS, heigthS);
                                    WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】保存成功", Color.Black);

                                }
                                catch (Exception)
                                {
                                    WriteInfo("产品【" + view.OrderProductName + "】的照片【" + photo.PhotoName + "】导出失败,请重新导出,或是手动拷贝!", Color.Red);
                                }
                            }
                            else
                            {
                                WriteInfo("产品【" + view.OrderProductName + "】包含非照片格式文件【" + photo.PhotoName + "】", Color.Black);
                            }
                            intCurrPoint += photoStep;
                            SetProcessPoint(intCurrPoint);
                            ///合并单元格
                            ///
                            for (int i = 1; i < 7; i++)
                            {
                                excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, i, 8 * (iCount + 1) + 5, i);
                            }
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 1, 8 * (iCount + 1) + 1, 1);
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 2, 8 * (iCount + 1) + 1, 2);
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 3, 8 * (iCount + 1) + 1, 3);
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 4, 8 * (iCount + 1) + 1, 4);
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 5, 8 * (iCount + 1) + 1, 5);
                            //excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 6, 8 * (iCount + 1) + 1, 6);
                            excelEdit.UniteCells(currSheet, photoInfoStartRow + 2 + intCount, 6, 8 * (iCount + 1) + 5, 8);

                        }


                    }
                }
                SetProcessPoint(100);

                excelEdit.SaveAs(savePath + "\\" + OutShopName + DateTime.Now.ToString("yyyyMMddHHmmss") + ExprotGridName + ".xls");
                WriteInfo("成功导出 （" + ExportList.Count + "）个产品", Color.Black);
                //RARsave(savePath,savePath,currOperPath);
            }


            finally
            {
                RasterCodecs.Shutdown();
                excelEdit.Close();

            }
            try
            {
                RARsaveOther(savePath, rarSavePath, currOperPath);
            }
            catch (Exception exxx)
            {
                MessageBox.Show("压缩出错，请检查有无RAR软件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            if (File.Exists(rarSavePath + "\\" + currOperPath + ".rar"))
            {
                DeleteDirectory(rarSavePath + "\\" + currOperPath);
            }
        }
        static void DeleteDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0)
                {
                    if (Directory.Exists(dir))
                    {
                        Directory.Delete(dir);
                    }
                    return;
                }
                else if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length != 0)
                {
                    string[] strFiles = Directory.GetFiles(dir);
                    foreach (string str in strFiles)
                    {

                        File.Delete(str);


                    }
                }

                foreach (string var in Directory.GetDirectories(dir))
                {

                    DeleteDirectory(var);
                }
                foreach (string var in Directory.GetFiles(dir))
                {
                    if (File.Exists(var))
                    {
                        File.Delete(var);
                    }
                    //File.Delete(var);
                }
                if (Directory.Exists(dir))
                {
                    Directory.Delete(dir);
                }
            }
            // Directory.Delete(dir);
        }
        private delegate void ShowMessage(string str, Color inColor);
        public void WriteInfo(string str, Color inColor)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ShowMessage(WriteInfo), new object[] { str, inColor });
            }
            else
            {
                richTextBoxInfo.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + str + Environment.NewLine +
                                       richTextBoxInfo.Text;
            }
        }

        private delegate void DelegateSetProcessValue(int value);

        void SetProcessPoint(int inValue)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new DelegateSetProcessValue(SetProcessPoint), new object[] { inValue });
            }
            else
            {
                if (inValue > 100)
                {
                    inValue = 100;
                }
                progressBar1.Value = inValue;

            }
        }

        public void RARsave(string path, string rarPatch, string rarName)
        {
            String the_rar;
            RegistryKey the_Reg;
            Object the_Obj;
            String the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            try
            {
                the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                the_rar = the_rar.Substring(1, the_rar.Length - 7);
                Directory.CreateDirectory(path);
                //命令参数
                //the_Info = " a    " + rarName + "  " + @"C:Test&<28;70821.txt"; //文件压缩
                //the_Info = " a -r " + rarName + " " + patch  ;
                the_Info = string.Format("a {0} {1} -r",
                                     rarName,
                                     path);

                the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //打包文件存放目录
                the_StartInfo.WorkingDirectory = rarPatch;
                //the_StartInfo.UseShellExecute = false;
                the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;

                the_Process.Start();
                the_Process.WaitForExit();//无限期等待进程 winrar.exe 退出


                the_Process.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void RARsaveOther(string path, string rarPatch, string rarName)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "Winrar.exe";
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.WorkingDirectory = rarPatch;
            process.StartInfo.Arguments = "a " + rarName + " " + rarName;
            process.StartInfo.ErrorDialog = false;
            process.Start();

            process.WaitForExit();


        }

        private void simpleButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
